import axios from "axios";
import { MessageBox, Message } from "element-ui";
import store from "@/store";
import { getToken } from "@/utils/auth";
import qs from "qs";
// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  withCredentials: true, // send cookies when cross-domain requests
  timeout: 300000 // request timeout
});

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    config.headers["Content-Type"] = "application/json";
    if (store.getters.token) {
      config.headers["Authorization"] = "Bearer " + getToken();
    }
    if (config.method === "get") {
      // 如果是get请求，且params是数组类型如arr=[1,2]，则转换成arr=1&arr=2
      config.paramsSerializer = function (params) {
        return qs.stringify(params, { arrayFormat: "repeat" });
      };
    }
    return config;
  },
  error => {
    // do something with request error
    console.log(error); // for debug
    return Promise.reject(error);
  }
);

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response.data;
    console.log('res+++++: ', res);
    if (response.headers["content-type"] === "application/vnd.ms-excel") {
      return res;
    }
    // if the custom code is not 20000, it is judged as an error.
    if (res.code !== 1) {
      Message({
        message: res.message || "未知错误",
        type: "error",
        duration: 5 * 1000
      });
      if (res.code === 401) {
        // to re-login
        MessageBox.confirm("登录信息已过期，请重新登录！", "重新登录确认", {
          confirmButtonText: "重新登录",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          store.dispatch("user/resetToken").then(() => {
            location.reload();
          });
        });
      }
      if (res.code === 403) {
        // 未授权
        Message({
          message: "请求无权限",
          type: "error",
          duration: 3 * 1000
        });
      }
      return res
      // return Promise.reject(res);
      // return Promise.reject(new Error(res.message || "Error"));
    } else {
      return res;
    }
  },
  error => {
    console.log("err" + error); // for debug
    Message({
      message: "出错啦！" + error,
      type: "error",
      duration: 3 * 1000
    });

    if (error.response.status != null && error.response.status != undefined) {
      switch (error.response.status) {
        // 401: 未登录
        // 未登录则跳转登录页面，并携带当前页面的路径
        // 在登录成功后返回当前页面，这一步需要在登录页操作。
        case 401:
          MessageBox.confirm("您未登录或登录信息已过期", "重新登录确认", {
            confirmButtonText: "重新登录",
            cancelButtonText: "取消",
            type: "warning"
          }).then(() => {
            store.dispatch("user/resetToken").then(() => {
              location.reload();
            });
          });
          break;
        // 403 token过期
        // 登录过期对用户进行提示
        // 清除本地token和清空vuex中token对象
        // 跳转登录页面
        case 403:
          Message({
            message: "请求失败，无权限操作",
            type: "error",
            duration: 3 * 1000
          });
          break;
        // 404请求不存在
        case 404:
          Message({
            message: "网络请求不存在",
            type: "error",
            duration: 3 * 1000
          });
          break;
        case 429:
          Message({
            message: "请求过于频繁，请稍候再试",
            type: "error",
            duration: 3 * 1000
          });
          break;
        // 其他错误，直接抛出错误提示
        default:
          Message({
            message: error.message,
            type: "error",
            duration: 3 * 1000
          });
      }
    }
    return Promise.reject(error);
  }
);

export default service;
